<template>
  <div>
    <h2>V2购物车的组件分离</h2>
    <div class="table">
      <my-header
        :checkedAll="checkedAll"
        @setCheckedAll="setCheckedAll"
      ></my-header>
      <my-list :list="list" @calc="calc" @delListById="delListById"></my-list>
      <my-footer :num="num" :price="price"></my-footer>
    </div>
  </div>
</template>

<script>
import myHeader from "../components/shoppingcar/myHeader.vue";
import myList from "../components/shoppingcar/myList.vue";
import myFooter from "../components/shoppingcar/myFooter.vue";
export default {
  methods: {
    setCheckedAll(flag) {
      //状态
      this.list.forEach((item) => {
        item.checked = flag;
      });
    },
    calc({ item, num }) {
      //加减法  对象解构
      item.goodsnum = item.goodsnum + num;
    },
    delListById(id) {
      //过滤
      this.list = this.list.filter((item) => item.id !== id);
    },
  },
  watch: {
    list: {
      deep: true,
      handler() {
        this.checkedAll = this.list.length
          ? this.list.every((item) => item.checked)
          : false; //全部选中 才为true
      },
    },
  },
  computed: {
    num() {
      let checkedList = this.list.filter((item) => item.checked); //找到选中的集合
      if (checkedList.length) {
        //判断长度
        return checkedList.map((item) => item.goodsnum).reduce((a, b) => a + b);
      }
      return 0;
    },
    price() {
      let checkedList = this.list.filter((item) => item.checked); //找到选中的集合
      if (checkedList.length) {
        //判断长度
        return checkedList
          .map((item) => item.goodsnum * item.goodsprice)
          .reduce((a, b) => a + b);
      }
      return 0;
    },
  },
  data() {
    return {
      checkedAll: false, //全选
      list: [
        {
          id: 1,
          goodsname: "商品名称一",
          goodsprice: 100,
          goodsnum: 10,
          checked: false,
        },
        {
          id: 2,
          goodsname: "商品名称二",
          goodsprice: 200,
          goodsnum: 1,
          checked: false,
        },
        {
          id: 3,
          goodsname: "商品名称三",
          goodsprice: 300,
          goodsnum: 1,
          checked: false,
        },
      ],
    };
  },

  components: {
    myHeader,
    myList,
    myFooter,
  },
};
</script>

<style>
.table {
  width: 100%;
}
.tr {
  display: flex;
}
.tr .td {
  flex: 1;
  text-align: center;
  line-height: 40px;
  background-color: black;
  color: white;
}
</style>
